package com.educate.common.filter;

import cn.hutool.core.util.StrUtil;
import com.educate.common.lang.Const;
import com.educate.common.security.CaptchaException;
import com.educate.common.handler.LoginFailureHandler;
import com.educate.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yjj
 * @date 2021/11/8
 * @description: 验证码过滤器
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if("/login".equals(requestURI) && "POST".equals(request.getMethod())){
            //校验验证码
            try {
                validate(request);
            } catch (CaptchaException e) {
               loginFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
        filterChain.doFilter(request,response);

    }

    private void validate(HttpServletRequest request){
        String key = request.getParameter("key");
        String code = request.getParameter("code");
        if(StrUtil.isBlank(key) || StrUtil.isBlank(code)){
            throw new CaptchaException("验证码错误！");
        }
        if(!code.equals(redisUtil.hget(Const.CAPTCHA_KEY,key))){
            throw new CaptchaException("验证码错误！");
        }
        //移除redis中的验证码
        redisUtil.hdel(Const.CAPTCHA_KEY,key);
    }
}
